<?php


namespace App\Model\Repository;


use App\Constant\Env;
use App\Model\Base\Api;

/**
 * Class ApiRepository
 * @package App\Model\Repository
 * @property ApiRequestBodyRepository[]|\Illuminate\Database\Eloquent\Relations\HasMany $request
 * @property ApiResponseBodyRepository $response
 * @property ApiProjectRepository $project
 */
class ApiRepository extends Api
{
    public function category()
    {
        return $this->belongsTo(ApiCategoryRepository::class, 'category_id', 'category_id');
    }

    public function project()
    {
        return $this->belongsTo(ApiProjectRepository::class, 'project_id', 'project_id');
    }

    public function request()
    {
        return $this->hasMany(ApiRequestBodyRepository::class, 'api_id', 'api_id');
    }

    /**
     * 读取接口id和接口名称映射数组
     * @return array
     */
    public static function getApiMap()
    {
        return collect(self::all()->toArray())->mapWithKeys(function ($item) {
            return [$item['api_id'] => $item['api_name']];
        })->all();
    }

    public function response()
    {
        return $this->hasOne(ApiResponseBodyRepository::class, 'api_id', 'api_id');
    }

    /**
     * 请求完整访问路径
     * @param string $env
     * @return string
     */
    public function getRequestUrl($env = Env::ENV_DEV)
    {
        $var = ApiVarRepository::where([
            ['name', '=', $this->getDomain()],
            ['env', '=', $env],
        ])->first();
        return rtrim($var->getValue(), '/') . '/' . ltrim($this->getPath(), '/');
    }
}